﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.UI.WebControls;
using Brettle.Web.NeatUpload;
using mojoPortal.Web;
using Resources;
using mojoPortal.Web.Framework;
using ud_Utilities;
using ud_ImageSlideShow.Data;

namespace ud_ImageSlideShow
{
    public partial class ImageSlideShowEdit : mojoBasePage
    {
        private int moduleId = -1;
        private int pageId = -1;
        private ImageSlideShow item = new ImageSlideShow();
        private Guid itemGuid = Guid.Empty;
        readonly DBImageSlideShow repository = new DBImageSlideShow();
        protected string DeleteLinkText = ImageSlideShowResource.ButtonDelete;
        protected string EditLinkText = ImageSlideShowResource.ButtonEdit;

        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
        }

        override protected void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Load += Page_Load;
            btnSave.Click += btnSave_Click;
            gvItems.RowCommand += gvItems_RowCommand;
            gvItems.RowDataBound += gvItems_RowDataBound;
            gvItems.PageIndexChanging += gvItems_PageIndexChanging;
            btnNew.Click += btnNew_Click;
            btnDelete.Click += btnDelete_Click;
            bool showLeftColumnAdmin = ConfigHelper.GetBoolProperty("ShowLeftColumnAdmin", false);
            bool showRightColumnAdmin = ConfigHelper.GetBoolProperty("ShowRightColumnAdmin", false);
            bool showTopColumnAdmin = ConfigHelper.GetBoolProperty("ShowTopColumnAdmin", false);
            bool showBottomColumnAdmin = ConfigHelper.GetBoolProperty("ShowBottomColumnAdmin", false);
            int showCenterColumnAdmin = ConfigHelper.GetIntProperty("ShowCenterColumnAdmin", 0);
            LoadSideContent(showLeftColumnAdmin, showRightColumnAdmin, showTopColumnAdmin, showBottomColumnAdmin, showCenterColumnAdmin);
        }

        #endregion

        private void Page_Load(object sender, EventArgs e)
        {
            Page.EnableViewState = true;
            LoadSettings();
            PopulateLabels();
            PopulateControls();
        }

        private void PopulateControls()
        {
            BindTarget();
            BindData();
            BindEdit();
        }

        private void BindTarget()
        {
            if (Page.IsPostBack) return;
            ListItemCollection lic = new ListItemCollection
                                         {
                                             new ListItem("Self", "_self"),
                                             new ListItem("New", "_blank")
                                         };
            ddlTarget.DataSource = lic;
            ddlTarget.DataTextField = "Text";
            ddlTarget.DataValueField = "Value";
            ddlTarget.DataBind();
        }

        void btnDelete_Click(object sender, EventArgs e)
        {
            if (item == null)
            {
                item = repository.GetOne(itemGuid);
            }
            DeleteImageSlideShowFromServer(item.Url);
            repository.Delete(itemGuid);
            Refresh(string.Empty);
        }

        void btnNew_Click(object sender, EventArgs e)
        {
            Refresh(string.Empty);
        }

        private void BindEdit()
        {
            if (Page.IsPostBack || itemGuid == Guid.Empty) return;
            item = repository.GetOne(itemGuid);
            if (item == null) return;
            txtName.Text = item.Name;
            txtSortOrder.Text = item.SortOrder.ToString();
            chkIsShow.Checked = item.IsShow;
            txtLink.Text = item.Link;
            ddlTarget.Items.FindByValue(item.LinkTarget).Selected = true;
            divImageSlideShow.Visible = true;
            string link = ImageSiteRoot + "/" + ConfigurationManager.AppSettings["ImageSlideShowFolder"] + item.Url;
            imgItem.ImageUrl = link;
            imgItem.AlternateText = item.Name;
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            String pathToApplicationsFolder
                = HttpContext.Current.Server.MapPath(
                "~/" + ConfigurationManager.AppSettings["ImageSlideShowFolder"]);
            if (!Directory.Exists(pathToApplicationsFolder))
            {
                Directory.CreateDirectory(pathToApplicationsFolder);
            }
            string fileName;
            string error = string.Empty;
            if (itemGuid == Guid.Empty)
            {
                if (!nifImageSlideShow.HasFile)
                {
                    lblImageURLError.Text = ImageSlideShowResource.NoFileWarning;
                    return;
                }
                if (SaveImageURL(ref error, out fileName))
                {
                    repository.Create(moduleId, 0, txtName.Text, fileName, txtLink.Text, ddlTarget.SelectedValue,
                                      chkIsShow.Checked, Convert.ToInt32(txtSortOrder.Text));
                    Refresh(string.Empty);
                }
                else
                {
                    lblImageURLError.Visible = true;
                    lblImageURLError.Text = error;
                }
            }
            else
            {
                item = repository.GetOne(itemGuid);
                SaveImageURL(ref error, out fileName);
                fileName = fileName == string.Empty ? item.Url : fileName;
                repository.Update(itemGuid, 0, txtName.Text, fileName, txtLink.Text, ddlTarget.SelectedValue,
                                  chkIsShow.Checked, Convert.ToInt32(txtSortOrder.Text));
                itemGuid = Guid.Empty;
                Refresh(string.Empty);
            }
        }

        private void Refresh(string itemID)
        {
            if (itemID == string.Empty)
            {
                WebUtils.SetupRedirect(this, SiteRoot + "/ImageSlideShow/Admin/ImageSlideShowEdit.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString());
            }
            else
            {
                WebUtils.SetupRedirect(this, SiteRoot + "/ImageSlideShow/Admin/ImageSlideShowEdit.aspx?pageid="
                    + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString() + "&itemid=" + itemID);
            }
        }

        private void LoadSettings()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", moduleId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", true, moduleId);
            itemGuid = WebUtils.ParseGuidFromQueryString("itemid", itemGuid);
        }

        private void BindData()
        {
            List<ImageSlideShow> listImageSlideShow = repository.GetAll(moduleId);
            gvItems.DataSource = listImageSlideShow;
            gvItems.DataBind();
            gvItems.AllowPaging = listImageSlideShow.Count > gvItems.PageSize;
        }

        private void PopulateLabels()
        {
            PageTitle = SiteUtils.FormatPageTitle(siteSettings, ImageSlideShowResource.ImageSlideShowEditPage);
            lblTitle.Text = ImageSlideShowResource.ImageSlideShowEditPage;
            btnSave.Text = ImageSlideShowResource.ButtonSave;
            btnNew.Text = ImageSlideShowResource.ButtonNew;
            btnDelete.Text = ImageSlideShowResource.ButtonDelete;
            lblImageURLError.Text = ImageSlideShowResource.ImageUrlErrorLabel + ConfigurationManager.AppSettings["AllowedImageSlideShowFileExtensions"]
                + ImageSlideShowResource.ImageInfoSpliter + ImageSlideShowResource.ImageUrlErrorLabelFileSize + ConfigurationManager.AppSettings["AllowedImageSlideShowSize"] + @" KB";

            gvItems.Columns[3].HeaderText = ImageSlideShowResource.Image;
            UIHelper.DisableButtonAfterClick(
                btnSave,
                ImageSlideShowResource.ButtonPleaseWait,
                Page.ClientScript.GetPostBackEventReference(btnSave, string.Empty)
                );
            if (itemGuid != Guid.Empty)
            {
                btnDelete.Visible = true;
                Utilities.AddConfirmButton(btnDelete, ImageSlideShowResource.DeleteConfirmWarning);
            }
            lblImageURLError.ForeColor = Color.Blue;
        }

        private bool SaveImageURL(ref string error, out string fileName)
        {
            bool flag = false;
            int width = 0;
            int height = 0;
            fileName = string.Empty;
            try
            {
                //Check valid file upload
                if (nifImageSlideShow.FileName.Length > 0)
                {
                    string fileExtension = Path.GetExtension(nifImageSlideShow.FileName);
                    Double fileSize = nifImageSlideShow.ContentLength / 1024;

                    //Kiem tra ten mo rong file upload
                    if (!Utilities.IsValidFileExtension(fileExtension, "AllowedImageSlideShowFileExtensions"))
                    {
                        error = ImageSlideShowResource.ImageUrlErrorFileExtension;
                        return false;
                    }
                    //Kiem tra kich thuoc file upload
                    if (!Utilities.IsValidFileSize(fileSize, "AllowedImageSlideShowSize"))
                    {
                        error = ImageSlideShowResource.ImageUrlErrorFileSize + ConfigurationManager.AppSettings["AllowedImageSlideShowSize"] + " KB";
                        return false;
                    }
                    string path = Server.MapPath("~/" + ConfigurationManager.AppSettings["ImageSlideShowFolder"]);
                    string guid = Guid.NewGuid().ToString().Replace("-", "").ToUpper();
                    string fileTemp = path + guid + "_temp" + fileExtension;
                    nifImageSlideShow.MoveTo(fileTemp, MoveToOptions.Overwrite);
                    using (System.Drawing.Image image = System.Drawing.Image.FromFile(fileTemp))
                    {
                        int resizeWidth = Convert.ToInt32(ConfigurationManager.AppSettings["ImageSlideShowMaxWidth"]);
                        int resizeHeight = Convert.ToInt32(ConfigurationManager.AppSettings["ImageSlideShowMaxHeight"]);
                        int thumbnailWidth = Convert.ToInt32(ConfigurationManager.AppSettings["ImageSlideShowMaxThumbnailWidth"]);
                        int thumbnailHeight = Convert.ToInt32(ConfigurationManager.AppSettings["ImageSlideShowMaxThumbnailHeight"]);
                        Utilities.ResizeImage(ref width, ref height, resizeWidth, resizeHeight, image.Width, image.Height);
                        fileName = path + guid + "_t" + fileExtension;
                        if (height != 0)
                        {
                            using (Bitmap bitmap = new Bitmap(image, width, height))
                            {
                                bitmap.Save(fileName, image.RawFormat);
                            }
                        }
                        else
                        {
                            using (Bitmap bitmap = new Bitmap(image, image.Width, image.Height))
                            {
                                bitmap.Save(fileName, image.RawFormat);
                            }
                        }

                        Utilities.ResizeImage(ref width, ref height, thumbnailWidth, thumbnailHeight, image.Width, image.Height);
                        fileName = path + guid + fileExtension;
                        if (height != 0)
                        {
                            using (Bitmap bitmap = new Bitmap(image, width, height))
                            {
                                bitmap.Save(fileName, image.RawFormat);
                            }
                        }
                        else
                        {
                            using (Bitmap bitmap = new Bitmap(image, image.Width, image.Height))
                            {
                                bitmap.Save(fileName, image.RawFormat);
                            }
                        }
                    }
                    if (File.Exists(fileTemp))
                    {
                        File.Delete(fileTemp);
                    }
                    fileName = guid + fileExtension;
                    if (item.Url != null)
                    {
                        DeleteImageSlideShowFromServer(item.Url);
                    }
                    flag = true;
                }
                else
                {
                    flag = true;
                }
            }
            catch (Exception e)
            {
                error = e.Message;
            }
            return flag;
        }

        private void DeleteImageSlideShowFromServer(string imageURL)
        {
            string thumbnailImageURL = Request.PhysicalApplicationPath + ConfigurationManager.AppSettings["ImageSlideShowFolder"] + imageURL;
            thumbnailImageURL = thumbnailImageURL.Replace("/", "\\");
            string url = thumbnailImageURL.Substring(0, thumbnailImageURL.LastIndexOf(".")) + "_t" + thumbnailImageURL.Substring(thumbnailImageURL.LastIndexOf("."));
            if (File.Exists(url))
            {
                File.Delete(url);
            }
            if (File.Exists(thumbnailImageURL))
            {
                File.Delete(thumbnailImageURL);
            }
        }


        void gvItems_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("EditItem"))
            {
                itemGuid = new Guid(e.CommandArgument.ToString());
                Refresh(itemGuid.ToString());
            }
            else if (e.CommandName.Equals("DeleteItem"))
            {
                itemGuid = new Guid(e.CommandArgument.ToString());
                if (item.Url == null) { item = repository.GetOne(itemGuid); }
                DeleteImageSlideShowFromServer(item.Url);
                repository.Delete(itemGuid);
                WebUtils.SetupRedirect(this, Request.RawUrl);
            }
        }

        void gvItems_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvItems.PageIndex = e.NewPageIndex;
            BindData();
        }

        void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton ibtnDelete = e.Row.FindControl("ibtnDelete") as ImageButton;
                Utilities.AddConfirmButton(ibtnDelete, ImageSlideShowResource.DeleteConfirmWarning);
            }
        }

        protected override void OnError(EventArgs e)
        {
            Exception lastError = Server.GetLastError();
            if ((lastError != null) && (lastError is NullReferenceException) && Page.IsPostBack)
            {
                if (lastError.StackTrace.Contains("Recaptcha"))
                {
                    Server.ClearError();
                    WebUtils.SetupRedirect(this, Request.RawUrl);
                }
            }
        }

    }
}